import { useCartStore } from '@/stores/cart'
import { ref } from 'vue'
import { Dialog, Toast } from 'vant';


/**
 * 购物车业务
 */



export const useCart = (id: number) => {
    const checkAllState = ref(false)
    const store = useCartStore()
    const cartList = ref(store.cartList) // 购物车商品列表
    const disabled = ref(false)
    const cartbutt=ref(true)

    //点击全选
    const checkAll = () => {
        // checkAllState.value = !checkAllState.value // 1. 设置全选状态
        console.log('点击全选后全选状态', checkAllState.value);

        // 2. 设置所有复选框状态
        cartList.value.forEach(item => {
            item.state = checkAllState.value
        })
        showtotalPrice()
        cartbutt.value=false
    }
    // 点击单选
    const onSingleCheck = (id: number) => {

        //更新单选状态
        // const product = cartList.value.find(item => item.id == id)

        //设置全选状态
        checkAllState.value = cartList.value.every(item => item.state == true)
        console.log('单选全选后的全选', checkAllState.value);

        showtotalPrice()
        cartbutt.value=false

    }

    // 总价
    const showtotalPrice = () => {
        const total = cartList.value.reduce((previous, current) => previous + (current.state ? current.price * current.num * 100 : 0), 0)

        return total
    }
    const total = showtotalPrice()

    // 删除商品
    const onDelete = (id: number) => {
        console.log(cartList.value);
        const deleproduct = cartList.value.find(item => item.id == id)
        console.log(deleproduct);
        cartList.value = cartList.value.filter(cartList => cartList.id != deleproduct.id)
        console.log(cartList.value);


    }



    //选择并弹出删除框
    const beforeClose = ({ position }) => {
        switch (position) {
            case 'left':
            case 'cell':
            case 'outside':
                return true;
            case 'right':
                return new Promise((resolve) => {
                    Dialog.confirm({
                        title: '确定删除吗？',
                    }).then(resolve);
                });
        }

    };

    // 订单界面商品列表
    const checkList = (state: boolean) => {
        console.log(cartList.value);
        const productList = cartList.value.filter(item => item.state == true)
        // console.log(productList);
        return productList

    }

    const productList = checkList()

    return { cartList, beforeClose, onSingleCheck, checkAll, onDelete, checkList,cartbutt, total, productList, showtotalPrice, checkAllState, disabled }
}
